﻿using Microsoft.EntityFrameworkCore;

using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

using ZFB.Models;
using ZFB.Models.EntityConfig;
using ZFB.Repository.City;

namespace ZFB.Repository.AdminUser
{
    public class AdminUserRepository : BaseRepository<T_AdminUsers>, IAdminUserRepository
    {
        private readonly MyDbContext _dbContext;
        public AdminUserRepository(MyDbContext dbContext) : base(dbContext)
        {
            _dbContext = dbContext;
        }
        public override async Task<List<T_AdminUsers>> GetListAsync()
        {
            return await _dbContext.T_AdminUsers
                .AsNoTracking()
                .Where(e => !e.IsDeleted)
                .Include(e => e.T_Cities)
                .ToListAsync();
        }
        public async override Task<T_AdminUsers> GetModelAsync(Expression<Func<T_AdminUsers, bool>> whereExpression)
        {
            return await _dbContext.T_AdminUsers
                 //.AsNoTracking()
                 .Where(e => !e.IsDeleted)
                 .Include(e => e.T_Cities)
                 .Include(e => e.T_Roles)
                 .SingleOrDefaultAsync(whereExpression);
        }
        public override async Task<List<T_AdminUsers>> GetListAsync(Expression<Func<T_AdminUsers, bool>> whereExpression)
        {
            return await _dbContext.T_AdminUsers
                .AsNoTracking()
                .Where(e => !e.IsDeleted)
                .Where(whereExpression)
                .Include(e => e.T_Cities)
                .Include(e => e.T_Roles)
                .ToListAsync();
        }

        public bool HasPermissionAsync(long id, string permissionName)
        {
            var perm = _dbContext.T_AdminUsers
                .AsNoTracking()
                .Where(e => !e.IsDeleted)
                .Where(e => e.Id == id)
                .SelectMany(e => e.T_Roles
                .SelectMany(e => e.T_Permissions))
                .Any(e => e.Name == permissionName);
            if (perm) return true;
            return false;
        }
    }
}
